package com.zhs.xyzsdk.wizards;

import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.*;
import org.eclipse.core.resources.*;

public class NewProjectWizardPage extends WizardPage {
	private Text nameField;
	private boolean includeCom;
	private boolean includeSrcRefs;

	public NewProjectWizardPage(ISelection selection) {
		super("wizardPage");
		includeCom = false;
		includeSrcRefs = true;
		setTitle("New Reference Project");
		setDescription("This wizard creates a new reference project.");
	}

	public void createControl(Composite parent) {
		Composite container = new Composite(parent, 0);
		GridLayout layout = new GridLayout();
		layout.numColumns = 3;
		container.setLayout(layout);
		Label nameLabel = new Label(container, 0);
		nameLabel.setLayoutData(new GridData(128));
		nameLabel.setText("Project Name:");
		nameField = new Text(container, 2048);
		nameField.addModifyListener(new ModifyListener() {

			public void modifyText(ModifyEvent e) {
				updatePageComplete();
			}

		});
		nameField.setToolTipText("Enter the name of the new project");
		GridData gridData = new GridData(768);
		gridData.horizontalSpan = 2;
		nameField.setLayoutData(gridData);
		initContents();
		updatePageComplete();
		setControl(container);
	}

	private void initContents() {
		nameField.setText(newProjectName());
	}

	private String newProjectName() {
		String baseName = "newXYZProject";
		if (getProjectNamed(baseName) == null)
			return baseName;
		int index = 1;
		do {
			String name = baseName + index;
			if (getProjectNamed(name) == null)
				return name;
			index++;
		} while (true);
	}

	private Object getProjectNamed(String name) {
		IProject projects[] = ResourcesPlugin.getWorkspace().getRoot()
				.getProjects();
		for (int i = 0; i < projects.length; i++)
			if (projects[i].getName().equals(name))
				return projects[i];

		return null;
	}

	private void updatePageComplete() {
		String errMsg = validateContent();
		setErrorMessage(errMsg);
		setPageComplete(errMsg == null);
	}

	private String validateContent() {
		String text = getProjectName();
		if (text.length() == 0)
			return "Enter the name of the XYZ project to be created";
		if (getProjectNamed(text) != null)
			return "Project named " + text + " already exists";
		return null;
	}

	public String getProjectName() {
		return nameField.getText().trim();
	}

	public String getClasspathVariable() {
		return "ECLIPSE_HOME";
	}

	public boolean getIncludeCom() {
		return includeCom;
	}

	public boolean getIncludeSrcRefs() {
		return includeSrcRefs;
	}
}
